<template>
  <d2-container>
  <section>
     <el-main class="bg-white">
       <div class="search">
          <el-form label-position="right" :model="dataForm" :inline="true">
            <el-form-item class="el-form-item--mini">
              <el-input placeholder="请选择部门信息"
                style="width: 250px;"
                class="filter-item"
                size="mini"
                :suffix-icon="showTree?'el-icon-arrow-up':'el-icon-arrow-down'"
                @click.native="deptogglePanel($event)"
                v-model="departName">
                <template slot="prepend">选择部门</template>
              </el-input>
              <div v-if="showTree" class="objectTree w-160" ref="suoShuMenTree">
                <el-tree
                  :style="'height:'+containerHeight+'px'"
                  ref="departTree"
                  highlight-current
                  node-key="organizationId"
                  :data="dataList"
                  :expand-on-click-node="false"
                  :props="menuListTreeProps"
                  @node-click="selectDepart"
                  default-expand-all
                ></el-tree>
              </div>
            </el-form-item>
            <el-form-item class="el-form-item--mini">
              <el-radio-group v-model="dataForm.dateType" size="mini">
                <el-radio-button :label="item.date" v-for="(item, index) in Config.searchDate" :key="index">
                  {{item.label}}
                </el-radio-button>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="日期" label-width="40px" class="el-form-item--mini">
              <el-date-picker
                v-model="dataForm.date"
                placeholder="时间范围"
                style="width: 250px;"
                class="filter-item"
                size="mini"
                :picker-options="pickerOptions"
                :type="dataForm.dateType"
                suffix-icon="el-icon-date"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                clearable
                @keyup.enter.native="getAllDataList"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item class="el-form-item--mini">
              <el-select v-model="dataForm.energyType"  style="width: 100px;" placeholder="请选择"  size="mini">
                <el-option
                  v-for="(item, index) in meterTypeList" :key="index"
                  :label="item.paramValue"
                  :value="item.paramKey">
                </el-option>
              </el-select>
            </el-form-item>
            <!--<el-form-item class="el-form-item&#45;&#45;mini">-->
              <!--<el-button-group>-->
                <!--<el-button v-if="showEchatrt" size="mini" icon="el-icon-menu" @click="changeShowType">表格</el-button>-->
                <!--<el-button v-else size="mini" icon="el-icon-picture" @click="changeShowType">图表</el-button>-->
              <!--</el-button-group>-->
            <!--</el-form-item>-->
            <el-form-item class="el-form-item--mini">
              <el-button
                class="filter-item"
                type="primary"
                icon="el-icon-search"
                size="mini"
                @click="getAllDataList"
              >查询</el-button>
              <!--<el-button-->
                  <!--class="filter-item"-->
                  <!--type="primary"-->
                  <!--icon="el-icon-download"-->
                  <!--size="mini"-->
                  <!--@click="exoprtData"-->
              <!--&gt;导出</el-button>-->
            </el-form-item>
          </el-form>
       </div>
       <div v-show="showEchatrt">
          <el-row :gutter="10" style="margin-top:30px;">
            <el-col :span="16">
              <div id="chartOne" class="busi-chart"  :style="'height:'+chartHeight/2+'px;'">
              </div>
            </el-col>
            <el-col :span="8">
              <div id="chartTwo" class="busi-chart"  :style="'height:'+chartHeight/2+'px;'">
              </div>
            </el-col>
          </el-row>
          <el-row style="margin-top:30px;">
            <div id="chartThree" :style="'height:'+chartHeight/2+'px;'" class="busi-chart">
            </div>
          </el-row>
       </div>
       <div v-show="!showEchatrt" class="table">
          <el-table
            :data="departTableDataList"
            border
            :height="chartHeight"
            style="width: 100%; height: 400px;overflow:auto;"
          >
            <el-table-column prop="index" header-align="center" align="center"  width="70" label="序号"></el-table-column>
            <el-table-column
              prop="departName"
              header-align="center"
              align="center"
              label="部门名称"
            ></el-table-column>
             <el-table-column
              prop="energyTypeName"
              header-align="center"
              align="center"
              label="分类"
            ></el-table-column>
            <el-table-column
              prop="bqVal"
              header-align="center"
              align="center"
              label="本期用能"
            ></el-table-column>
            <el-table-column
              prop="tqVal"
              header-align="center"
              align="center"
              label="同期用能"
            ></el-table-column>
            <el-table-column
              prop="hqVal"
              header-align="center"
              align="center"
              label="环期用能"
            ></el-table-column>
            <el-table-column
              prop="tbPercent"
              header-align="center"
              align="center"
              label="同比比率"
            ></el-table-column>
            <el-table-column
              prop="hbPercent"
              header-align="center"
              align="center"
              label="环比比率"
            ></el-table-column>
             <el-table-column
              prop="date"
              header-align="center"
              align="center"
              label="时间"
            ></el-table-column>
          </el-table>
       </div>
     </el-main>
  </section>
  </d2-container>
</template>

<script>
import * as Util from "@/utils";
import Config from "@/utils/config"
import * as Echarts from 'echarts'
import Minix from './mixin'
export default {
  mixins:[Minix],
  data() {
    return {
      sored:true,
      Config:Config,
      dataForm: {
        date:'',
        dateType:'',
        energyType:''
      },
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        }
      },
      dateTime: "",
      customer_id: this.$store.state.customer_id,
      dataList:[],
      menuListTreeProps: {
        label: "organizationName",
        children: "children"
      },
      departName:'',
      departId:'',
      PdepartId:'',
      showTree:false,
      showEchatrt:true,
      meterTypeList:[],
      chartThreeData:{
        isTqData:true,//表示当前是同期还是环期
        bqDataList:[],//本期数值
        tqDataPercentList:[],//同期比率
        hqDataPercentList:[],//环期比率
        tqDataList:[],//同期数据
        hqDataList:[]//环期数据
      },
      sourceData:[],//未经处理的源数据
      departTableDataList:[],//表格数据
      businessChart:{
          chart:"",
          x:['A部门','B部门','C部门','D部门','E部门','F部门','G部门','H部门','I部门','J部门','K部门','M部门','N部门'],
          data:[[9,7,8,5,4,6,8,9,7,8,5,4,6]],
          warn:9,
          title:"用电统计"
      },
      businessChartTwo:{
          data:[{name:'部门1',value:21},{name:'部门2',value:13},{name:'部门3',value:21},{name:'部门4',value:16},{name:'部门5',value:21},],
          legendData:['部门1','部门2','部门3','部门4','部门5'],
          title:"部门用能比例"
      },
      businessChartThree:{
        title:'电-能耗对比',
        legendData:{
          right:140,
          data: ['同期','本期','同比']
        },
        xAxisData:['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
        yAxisName:['单位 kw/h','比率'],
        seriesData:{
          data1: [2.0, 4.9, 7.0, 23.2, 25.6, 76.7, 135.6, 162.2, 32.6, 20.0, 6.4, 3.3],
          data2:[2.6, 5.9, 9.0, 26.4, 28.7, 70.7, 175.6, 182.2, 48.7, 18.8, 6.0, 2.3],
          data3: [2.0, -2.2, 3.3, -4.5, 6.3, -10.2, 20.3, 23.4, 23.0, 16.5, 12.0, 6.2]
        },
        color:['#2BD597','#708DE5', '#F6AD35']
      },
      unit:'',
    };
  },
  computed: {
    containerHeight() {
      return Util.getClientHeight() - 143;
    },
    chartHeight(){
       return Util.getClientHeight() - 340;
    }
  },
  activated(){

  },
  created(){
    this.queryStatic('METER_TYPE');
    this.dataForm.dateType=Config.searchDate[0].date
  },
  watch:{
    'dataForm.energyType':function(newV,oldV){
      this.unit = this.meterTypeList.find(item => item.paramKey == newV).paramExt;
    },
    'dataForm.dateType'(newV,oldV){
      let str=''
      switch(newV){
        case 'date':
          str= Util.dateFormat('YYYY-mm-dd',new Date())
          break;
        case 'month':
          str=Util.dateFormat('YYYY-mm',new Date())
          break;
        case 'year':
          str=Util.dateFormat('YYYY',new Date())
          break;
      }
      this.dataForm.date=str
    }
  },
  methods: {
    exoprtData(){
      // 导出数据
      let header=['序号','部门','分类','本期用能','同期用能','环期用能','同比比率','环比比率','时间']
      let props=['index','departName','energyTypeName','bqVal','tqVal','hqVal','tbPercent','hbPercent','dataDetail']
      let fileName=`部门用${ this.meterTypeList.find(item=>item.paramKey==this.dataForm.energyType).paramValue}统计`
      this.export2Excel(header,props,fileName,this.departTableDataList)
    },
    export2Excel (tH, fi, fiNa, dataList) {
      var tHeader = tH
      var filterVal = fi
      var fileName = fiNa
      require.ensure([], () => {
        const {export_json_to_excel} = require('@/utils/Export2Excel.js')
        const list = dataList
        const data = this.formatJson(filterVal, list)
        export_json_to_excel(tHeader, data, fileName)
      })
    },
    formatJson (filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]))
    },
    changeShowType(){
      this.showEchatrt = !this.showEchatrt;
    },
    //一个借口返回所有的数据
    getAllDataList(){
       //查询数据
      //需要将日期格式化
      let date= this.dataForm.date?this.formarDate(this.dataForm.dateType,new Date(this.dataForm.date)):''
      let params = {
          // customerId: "115",
          // date: "202104",
          // dateType: "2",
          // meterType: "1",
          // porgId: "-1",
          // orgId:'1',
          customerId: this.$cookie.get("customer_id"),
          dateType:Config.searchDate.find(item=>item.date==this.dataForm.dateType).typeDesc,//1日2月3年
          date:date,
          meterType:this.dataForm.energyType,//分类type
          porgId:this.departId,
         // orgId:this.departId
      }
      this.$http({
        url: this.$http.adornUrl('/ecm/depart/list'),
        method: 'post',
        data: this.$http.adornData(params)
      }).then(({data}) => {
        if (data && data.code === 0) {
        // data.data=[
        //   {
        //     val: 8,
        //     orgName: "MBA",
        //     tqVal: 72,
        //     hqVal: 36,
        //     orgId: 2,
        //   },
        //   {
        //     val: 3,
        //     orgName: "总办",
        //     tqVal: 51,
        //     hqVal: 21,
        //     orgId: 1,
        //   }
        // ]
        this.handleDataList(data.data.values,data.data.child)
        this.sourceData=data.data
        }
      });
    },
    handleDataList(data,child){
      // 处理所有的数据
      this.businessChart={
          chart:"",
          x:[],
          data:[[]],
          title:""
      },
      this.businessChartTwo={
          data:[],
          legendData:[],
          title:""
      },
      this.businessChartThree={
        title:'',
        legendData:{
          right:140,
          data: []
        },
        xAxisData:[],
        yAxisName:[],
        seriesData:{
          data1: [],
          data2:[],
          data3: []
        },
        color:['#2BD597','#708DE5', '#F6AD35']
      }
      this.chartThreeData={
        isTqData:true,//表示当前是同期还是环期
        bqDataList:[],//本期数值
        tqDataPercentList:[],//同期比率
        hqDataPercentList:[],//环期比率
        tqDataList:[],//同期数据
        hqDataList:[]//环期数据
      }
      this.departTableDataList=[]
      let selectType=this.meterTypeList.find(item=>item.paramKey==this.dataForm.energyType).paramValue
      this.businessChart.title=`用${selectType}统计`
      this.businessChartTwo.title=`部门用${selectType}比例`
      this.businessChartThree.title=`${selectType}-能耗对比`
      this.businessChartThree.yAxisName=[`单位${this.unit}`,'比率'],
      data.forEach((item,index)=>{
        //图表一
        // this.businessChart.x.push(item.dateDetail)
        // this.businessChart.data[0].push(item.val)
        //图表三
        let tqP=item.tqVal?(((item.val-item.tqVal)/item.tqVal)*100):0
        let hqP=item.hqVal?(((item.val-item.hqVal)/item.hqVal)*100):0
        this.chartThreeData.tqDataPercentList.push(tqP.toFixed(2))//计算同期比率
        this.chartThreeData.hqDataPercentList.push(hqP.toFixed(2))//计算环期比率
        this.chartThreeData.bqDataList.push(item.val)
        this.chartThreeData.tqDataList.push(item.tqVal)
        this.chartThreeData.hqDataList.push(item.hqVal)
        this.businessChartThree.xAxisData.push(item.dateDetail)
        //表格数据
        this.departTableDataList.push(
           {
             index:index+1,
             departName:this.departName,
             energyTypeName:this.meterTypeList.find(item=>item.paramKey==this.dataForm.energyType).paramValue,
             dataDetail:item.dateDetail,
             bqVal:item.val+this.unit,
             tqVal:item.tqVal+this.unit,
             hqVal:item.hqVal+this.unit,
             tbPercent:tqP.toFixed(2)+'%',
             hbPercent:hqP.toFixed(2)+'%',
             date:this.formarDateStr(this.dataForm.dateType,new Date(this.dataForm.date))
           }
        )
      })
      child.forEach((item,index)=>{
         //图表二
        this.businessChartTwo.data.push({name:item.orgName,value:item.val});
        this.businessChartTwo.legendData.push(item.orgName);
        //图表一
        this.businessChart.x.push(item.orgName);
        this.businessChart.data[0].push(item.val);
      })
      this.initBarChartOne(this.businessChart,'chartOne');
      this.initBarChartTwo(this.businessChartTwo,'chartTwo');
      this.businessChartThree.legendData.data=['同期','本期','同比'];
      this.businessChartThree.seriesData.data1=this.chartThreeData.bqDataList;
      this.businessChartThree.seriesData.data2=this.chartThreeData.tqDataList;
      this.businessChartThree.seriesData.data3=this.chartThreeData.tqDataPercentList;
      this.initBarChartThree(this.businessChartThree,'chartThree');
    },
    drawChartOneSort(){
      //排序渲染
      let result = JSON.parse(JSON.stringify(this.sourceData.child))
      if(this.sored){
        result=result.sort((a,b)=>a.val-b.val);
        this.sored = false
      }else{
        this.sored = true
      }
      this.businessChart.x=[]
      this.businessChart.data[0]=[]
      result.forEach(item=>{
        this.businessChart.x.push(item.orgName)
        this.businessChart.data[0].push(item.val)
      })
      this.initBarChartOne(this.businessChart,'chartOne');
    },
    tongbiShow(){
      //展示同比数据
      this.businessChartThree.color=['#2BD597','#708DE5', '#F6AD35']
      this.businessChartThree.legendData.data=['同期','本期', '同比'];
      this.businessChartThree.seriesData.data2=this.chartThreeData.tqDataList;
      this.businessChartThree.seriesData.data3=this.chartThreeData.tqDataPercentList;
      this.initBarChartThree(this.businessChartThree,'chartThree');
    },
    huanbiShow(){
      this.businessChartThree.color= ['#35e2cc','#708DE5','#a76a0b'];
      this.businessChartThree.legendData.data=['环期','本期', '环比'];
      this.businessChartThree.seriesData.data2=this.chartThreeData.hqDataList;
      this.businessChartThree.seriesData.data3=this.chartThreeData.hqDataPercentList;
      this.initBarChartThree(this.businessChartThree,'chartThree');
    },
    deptogglePanel (event) {
      event || (event = window.event)
      event.stopPropagation
        ? event.stopPropagation()
        : (event.cancelBubble = true)
      this.showTree ? this.dephide() : this.depshow()
    },
    depshow () {
      this.showTree = true
      document.addEventListener('click', this.dephidePanel, false)
    },
    dephide () {
      this.showTree = false
      document.addEventListener('click', this.dephidePanel, false)
    },
    dephidePanel (e) {
      if (
        this.$refs.suoShuMenTree &&
        !this.$refs.suoShuMenTree.contains(e.target)
      ) {
        this.dephide()
      }
    },
    selectDepart (data) {
      this.departName = data.organizationName;
      this.departId=data.organizationId;
      this.PdepartId=data.parentOrgId;
      this.showTree = false
    },
    initBarChartOne(opt,obj){
        let self=this
        let option={
            grid:{
              x:50,
              y:30,
              x2:55,
              y2:25,
            },
            title:{
                text:opt.title,
                show:true,
                left:'center',
                top:5,
                textStyle:{
                    color:"#ccc",
                    fontSize:14,
                    fontFamily:"MicrosoftYaHei",
                    lineHeight:14,
                },
                padding:0,
            },
            tooltip: {
              trigger: 'item',
              formatter: '{b}:{c}kw/h'
            },
            toolbox: {
              show: true,
              top:-6,
              right:40,
              feature: {
                myTool1: {    //必须要my开头
                  show: true,
                  title: '排名',
                  iconStyle: {
                    borderColor: 'green'
                  },
                  icon:'image://',
                  onclick: function (){
                   self.drawChartOneSort()
                  }
                }
              }
            },
            legend:{
              right:80,
              top:-5,
              data:[{
                name:'电'
              },{
                name:'水'
              },{
                name:'气'
              },{
                name:'暖'
              }]

            },
            xAxis:{
                type:'category',
                data:opt.x,
                axisLine:{
                    lineStyle:{
                        color:"#2C73D2",
                        type:'solid',
                        width:0.5
                    },
                },
                axisLabel:{
                    color:"#ccc",
                    interval:0,
                },
                axisTick: {
                  show:false,
                  alignWithLabel: true
                }
            },
            yAxis:{
                type:'value',
                name:'单位 kw/h',
                data:opt.y,
                axisLabel:{
                    color:"#ccc",
                },
                axisLine:{
                    lineStyle:{
                        color:"#ccc",
                        type:'soild',
                        opacity:0,
                    }
                },
                axisLabel:{
                    formatter:function(value,index){
                      return value;
                    }
                },
                axisTick: {
                    show:false,
                    alignWithLabel: true
                },
                splitLine:{
                    lineStyle:{
                        color:"#2C73D2",
                        type:"dotted",
                        opacity:0.5,
                    }
                },
            },
            series: [{
                name: '电',
                type: 'bar',
                data: opt.data[0],
                barCategoryGap:'40%',
                itemStyle:{
                  normal: {
                    barBorderRadius:[14,14,0,0],
                  },
                }
            }],
          color:['#4C7EDF','#FFCC00', '#00CC33', '#D05454',]
        }
        opt.chart = Echarts.init(document.getElementById(obj));
        opt.chart.setOption(option);
    },
    initBarChartTwo(opt,obj){
        let option={
           grid:{
              x:10,
              y:15,
              x2:15,
              y2:15,
            },
            title:{
                text:opt.title,
                show:true,
                left:'center',
                top:5,
                textStyle:{
                    color:"#ccc",
                    fontSize:14,
                    fontFamily:"MicrosoftYaHei",
                    lineHeight:14,
                },
                padding:0,
            },
            tooltip: {
              trigger: 'item',
              formatter: '{a} <br/>{b} : {c} ({d}%)'
            },
            legend: {
              type: 'scroll',
              orient: 'vertical',
              right: 10,
              top: '24%',
              bottom: 20,
              data: opt.legendData
            },
            series: [{
              name: '部门用能比例',
              type: 'pie',
              radius: '85%',
              center: ['45%', '55%'],
              data: opt.data,
              label: {
                  show: false,
                  position: 'center',
                  normal: {
                    position: 'inner',
                    show : false
                  }
              },
              emphasis: {
                  itemStyle: {
                      shadowBlur: 10,
                      shadowOffsetX: 0,
                      shadowColor: 'rgba(0, 0, 0, 0.5)'
                  }
              },
              labelLine: {
                  show: false
              },
          }],
          color:['#708DE5','#2BD597', '#F6AD35','#708ce5', '#446cea', '#0bc783','#2bd597']
        }
        opt.chart = Echarts.init(document.getElementById(obj));
        opt.chart.setOption(option);
    },
    initBarChartThree(opt,obj){
      let self=this
      let option={
          grid:{
              x:50,
              y:25,
              x2:55,
              y2:25,
              top:60,
          },
          title:{
              text:opt.title,
              show:true,
              left:'center',
              textStyle:{
                  color:"#ccc",
                  fontSize:14,
                  fontFamily:"MicrosoftYaHei",
                  lineHeight:14,
              },
              padding:5,
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'cross',
              crossStyle: {
                  color: '#999'
              }
            }
          },
          toolbox: {
            show: true,
            right:30,
            feature: {
              myTool1: {    //必须要my开头
                show: true,
                title: '同比',
                iconStyle: {
                  borderColor: 'green'
                },
                icon:'image://',
              //   icon：''
                onclick: function (){
                  self.tongbiShow()
                }
              },
              myTool2: {    //必须要my开头
                show: true,
                title: '环比',
                iconStyle: {
                  borderColor: 'green'
                },
                icon:'image://',
                onclick: function (){
                  self.huanbiShow()
                }
              }
            }
          },
          legend: opt.legendData,
          xAxis: [
              {
                type: 'category',
                data: opt.xAxisData,
                axisPointer: {
                  type: 'shadow'
                }
              }
          ],
          yAxis: [
              {
                  type: 'value',
                  name: opt.yAxisName[0],
                  // min: 0,
                  // max: 250,
                  // interval: 50,
                  axisLabel: {
                      formatter: '{value}'
                  }
              },
              {
                  type: 'value',
                  name: opt.yAxisName[1],
                  // min: 0,
                  // max: 25,
                  // interval: 5,
                  axisLabel: {
                    formatter: '{value}'
                  }
              }
          ],
          series: [
              {
                name: opt.legendData.data[0],
                type: 'bar',
                data: opt.seriesData.data1,
                itemStyle:{
                  normal: {
                    barBorderRadius:[14,14,0,0],
                  },
                },
              },
              {
                name:  opt.legendData.data[1],
                type: 'bar',
                data: opt.seriesData.data2,
                itemStyle:{
                  normal: {
                    barBorderRadius:[14,14,0,0],
                  },
                },
              },
              {
                name:  opt.legendData.data[2],
                type: 'line',
                yAxisIndex: 1,
                data:opt.seriesData.data3
              }
          ],
        color:opt.color
      }
      opt.chart = Echarts.init(document.getElementById(obj));
      opt.chart.setOption(option);
    },
    /**
     * 获取参数枚举
     */
    queryStatic(type) {
      this.$http({
        url: this.$http.adornUrl('/sys/sysstaticdata/getList'),
        method: 'get',
        params: this.$http.adornParams({
          'code': type ,
          "customerId":this.$cookie.get('customer_id')
        })
      }).then(({data}) => {
        if (data && data.code === 0) {
          this.meterTypeList = data.page
          this.dataForm.energyType = data.page[0].paramKey
        } else {
          this.meterTypeList = []
        }
        this.getDepartList();
      });
    },
     // 获取部门数据列表
    getDepartList () {
      this.$http({
        url: this.$http.adornUrl('/ecs/ecsorganizationinfo/select'),
        method: 'get',
        params: this.$http.adornParams({
          'page': 1,
          'limit': 10000,
          'key': '',
          "customerId":this.$cookie.get('customer_id')
        })
      }).then(({data}) => {
        if (data && data.code === 0) {
          if(data.menuList.length>0){
            this.selectDepart(data.menuList.find(item=>item.organizationId==-1))
          }
          this.dataList =Util.treeDataTranslate(data.menuList,'organizationId','parentOrgId')
        } else {
          this.dataList = []
        }

        this.getAllDataList()
      })
    },

  },
};
</script>

<style scoped>
.search{
  padding: 20px 0px 5px 0px;
  border: 1px solid #f9f5f5;
  border-left: none;
  border-right: none;
}
.busi-chart{
    width: 100%;
    height: 250px;
    border:1px solid #f9f5f5;
    border-top: none;
}
.objectTree {
    margin-left: 89px;
    position: absolute;
    overflow: auto;
    z-index: 100;
    height: 200px;
    /* border: 1px solid #ddd; */
    line-height: normal;
    z-index: 204;
    box-shadow: 0px 0px 1px 1px #e2dfdf;
    margin-top: 3px;
    border-radius: 4px;
  background-color: white;
 }
 .w-160{
  width: 160px
 }
</style>
